import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/AddDizhi.dart';
import 'package:shop/shop/life/DizhiGuanli.dart';
import 'package:shop/shop/life/PayMima.dart';

class CartOrder extends StatefulWidget {
  List cartList=[];         //订单的购物车列表，用于遍历商品
  String merchantName="";   //店铺名字
  String merchantId='';     //店铺id
  double dabaofei=0.00;     //打包费
  String adId;              //地址ID
  var orRemark="";          //订单备注
  int cartsize=0;           //订单中商品的数量
  String zongjia='0';       //订单总价
  String catid;             // 购物车编号
  final String title;
  CartOrder({Key key,this.merchantId, this.title,this.catid,this.adId,this.orRemark,this.cartList,this.merchantName,this.dabaofei,this.cartsize,this.zongjia}) : super(key: key);


  @override
  _CartOrder createState() => _CartOrder(merchantId,catid,adId,orRemark,cartList,merchantName,dabaofei,cartsize,zongjia);
}

class _CartOrder extends State<CartOrder> {
  int cartsize=0;//购物车总件数
  String zongjia='0';
  List cartList=[];
  String adId;//收货地址ID
  String names;//规格
  String params;//规格下标
  String catid; // 购物车编号
  bool hasDefaultZiti=false;//是否有默认自提点
  double dabaofei=0.00;
  String merchantName;//店铺名字
  String merchantId;

  // 构造方法
  _CartOrder(merchantId,catid,adId,orRemark,cartList,merchantName,dabaofei,cartsize,zongjia){
    this.merchantId=merchantId;
    this.catid=catid;
    this.adId = adId;
    this.cartList=cartList;
    this.orRemark = orRemark;
    this.merchantName = merchantName;
    this.dabaofei = dabaofei;
    this.zongjia= zongjia;
    this.cartsize=cartsize;

    _onLoading(catid,orRemark);
  }
  // 查询的商品
  var obj = [];   // 购物车里面选择的商品
  var num=0;  // 购买的个数
  var allMoney=0.00;  //商品金额总和
  var price = 0.00;//商品价格
  dynamic yunfei = 0.00;//运费
  var userId="";//用户ID
  var orRemark="";//订单备注
  var address = {};//用户默认地址
  var zitiAddress = {};//用户默认自提点或选中的自提点
  int addressCode = 400;//判断是否有默认地址

  var _controller = TextEditingController();

  // 获取数据
  void _onLoading(gid,orRemark) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    allMoney = price + yunfei;
    if(adId!=null && adId!=""){
      var z = await HttpUtil().get("/app/address/getAddressById?id="+adId);//根究地址ID得地址信息
      if(z['code']==200){
        address = z['data'];
        addressCode = z['code'];
      }
    }else{
      var y = await HttpUtil().get("/app/address/getDefaultAddress?userId="+userId);//得用户默认收货地址
      addressCode = y['code'];
      if(y['code']==200){
        address = y['data'];
        adId = y['data']['id'];
      }
    }
    if(orRemark!=null && orRemark!=""){
      _controller = TextEditingController(text: orRemark);
    }
    setState(() {});
  }

  // 显示订单状态
  Widget judgeAddress(addressCode){
    if(addressCode==200){
      return GestureDetector(
        child: Container(
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(
                  child:  Row(
                    children: [
                      Icon(Icons.add_location),
                      Expanded(
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children:[
                              Row(
                                children: [
                                  Expanded(
                                      child: Text("${address['addressDetail']}",style: TextStyle(fontSize: 20),)
                                  )
                                ],
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text("${address['adName']}",style: TextStyle(fontSize: 15,color: Colors.black54)),
                                  Container(
                                      child: Text("${address['adPhone']}",style: TextStyle(fontSize: 15,color: Colors.black54))
                                  )
                                ],
                              ),
                            ]),
                      ),
                ],)
              ),
              Align(alignment: Alignment.centerRight,child: Icon(Icons.navigate_next),)  ,
            ],
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          )
      ),onTap: () async {
          Map value = await MyRoute.push(DizhiGuanli(type:2,gid:catid,orRemark: orRemark,));//跳地址管理页面
          print(value);
          setState(() {
            address['adName']=value['adName'];
            address['adPhone']=value['adPhone'];
            address['addressDetail']=value['addressDetail'];
            adId=value['id'];
          });
          },
      );
    }else if(addressCode==400){
      return GestureDetector(child: Container(
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Row(children: [
                Icon(Icons.add_location),
                Center(child: Text("快捷选择收货地址")),
              ],),
              Icon(Icons.navigate_next),
            ],
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
          )
      ),onTap: () async {
        Map value = await MyRoute.push(DizhiGuanli(type:2,gid:catid,orRemark: orRemark,));//跳地址管理页面
        setState(() {
          this.addressCode=200;
          address['adName']=value['adName'];
          address['adPhone']=value['adPhone'];
          address['addressDetail']=value['addressDetail'];
        });
      },);
    }
    return GestureDetector(child: Container(
        decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
        padding: EdgeInsets.all(10),
        child: Row(
          children: [
            Row(children: [
              Icon(Icons.add_location),
              Center(child: Text("设置收货地址")),
            ],),
            Icon(Icons.navigate_next),
          ],
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
        )
    ),onTap: () async {
      Map value = await MyRoute.push(DizhiGuanli(type:2,gid:catid,orRemark: orRemark,));//跳地址管理页面
      setState(() {
        this.addressCode=200;
        address['adName']=value['adName'];
        address['adPhone']=value['adPhone'];
        address['addressDetail']=value['addressDetail'];
      });
    },);
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        title: Text("提交订单"),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          new Expanded(
              child: Container(
                padding:EdgeInsets.all(10),
                child: ListView(
                  children: [
                    judgeAddress(addressCode),
                    Container(
                      decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.only(top: 10),
                      child: Column(
                        children: [
                          Row(children: [
                            Icon(Icons.card_giftcard),
                            Text(merchantName,style: TextStyle(fontSize: 15),)
                          ]),
                          // 动态点击的商品
                          Column(
                            children: _showCatGoods(cartList),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("打包费：",style: TextStyle(fontSize: 18),),
                              Row(
                                children: [
                                  Text("￥",style: TextStyle(fontSize: 14),),
                                  Text("${dabaofei.toString()}",style: TextStyle(fontSize: 18),)
                                ],
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("配送费：",style: TextStyle(fontSize: 18),),
                              Row(
                                children: [
                                  Text("￥",style: TextStyle(fontSize: 14),),
                                  Text("${yunfei}",style: TextStyle(fontSize: 18),)
                                ],
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("订单备注：",style: TextStyle(fontSize: 18)),
                              Expanded(child: TextField(
                                controller: _controller,
                                decoration: InputDecoration(
                                  hintText: "留言口味、偏好等要求",
                                ),
                                onChanged: (text){
                                  orRemark = text;
                                },
                              ))
                            ],)
                        ],
                      ),
                    ),
                  ],
                ),
                color: Colors.black12,
              )
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsetsDirectional.only(start: 10),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Text('总计：',style: TextStyle(color: Colors.red, fontSize: 14)),
                              Text("￥",style: TextStyle(color: Colors.red, fontSize: 14)),
                              Text("${zongjia}",style: TextStyle(color: Colors.red, fontSize: 18))
                            ],
                          ),
                          Text("共${cartsize}件")
                        ],
                      )
                    ),
                    GestureDetector(child:  Container(
                      alignment: Alignment.center,
                      child: new Text(
                        "立即付款",
                        style: TextStyle(color: Colors.white),
                      ),
                      width: 130,
                      height: 50,
                      color: Colors.red,
                    ),
                      onTap: () async {
                        String addressId = adId;//收货地址ID或自提点ID
                        if(addressId==null || addressId==""){
                          Fluttertoast.showToast(
                              msg: "请选择收货地址"
                          );
                        }else{
                          print("lalalalalallaalal");
                          // 购物车结算生成订单
                          var x = await HttpUtil().get("/waimai/mOder/catSubmitMOrder?userId=$userId&mid=$merchantId&orPeisongtype=2&orRemark=$orRemark&dabaofei=$dabaofei&peisongfei=0&orPrice=$zongjia&addressId="+adId);
                          if(x['code']==200){
                            String unionid = x['msg'];
                            MyRoute.push(PayMima(unionid: unionid,userId: userId,money: double.parse(zongjia),type:4));
                          }else{
                            Fluttertoast.showToast(msg: x['msg']);
                          }
                        }
                      },
                    )
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  // 显示购物车里面勾选的商品
  List<Widget> _showCatGoods(catlist){
    List<Widget> goodsList = [];
    for(int i=0;i<catlist.length;i++){
      goodsList.add(
        Container(
          decoration: BoxDecoration(
            border: Border(bottom: BorderSide(width: 1,color: Colors.grey)) ,
          ),
          child: Row(
            children: [
              Image.network(Config.getInstance().getHost()+catlist[i]['mgoods']['gimages'],width: 70,height: 70,),
              Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 10),
                        child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                width: ScreenUtil().setWidth(240),
                                height: ScreenUtil().setHeight(40),
                                child: Row(
                                  children: [
                                    Expanded(child: Text("${catlist[i]['mgoods']['gname']}",style: TextStyle(fontSize: 18),),),
                                  ],
                                ),
                              ),
                              Row(
                                children: [
                                  Text("￥",style: TextStyle(fontSize: 14)),
                                  Text("${catlist[i]['money']}",style: TextStyle(fontSize: 18))
                                ],
                              )
                            ]
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 10),
                        child: Row(children: [catlist[i]['guiges']==null? Text(""):Expanded(child: Text(getGuigeString(catlist[i]['mgoods']['guige'],catlist[i]['guigeparams']),maxLines: 2,overflow: TextOverflow.ellipsis,style: TextStyle(fontSize: 12,color: Colors.black54),)),],),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 10),
                        child: Row(children: [Text("X",style: TextStyle(fontSize: 10),),Text("${catlist[i]['scatNum']}",style: TextStyle(fontSize: 16))],),
                      )
                    ],
                  )
              ),
            ],
          ),
          // height: 80,
          height: ScreenUtil().setHeight(110),
        ),
      );
    }
    return goodsList;
  }

  //解析购物车商品的规格
  String getGuigeString(val,params){
    List list=json.decode(val);
    List param=json.decode(params);
    int size=param.length;
    String str='';
    for(int i=0;i<size;i++){
      String value=list[i]['value'];
      var array=value.split('-');
      str+=list[i]['name']+":"+array[param[i]]+"  ";
    }
    return str;
  }
}